package com.wocai.jrt.orgadmin.pay.service.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.Date;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vteba.common.exception.ServiceException;
import com.vteba.service.generic.impl.MyBatisServiceImpl;
import com.vteba.tx.jdbc.mybatis.spi.BaseDao;
import com.vteba.utils.common.BigDecimalUtils;
import com.vteba.utils.common.PropUtils;
import com.vteba.utils.date.DateUtils;
import com.vteba.utils.id.ObjectId;
import com.vteba.web.action.JsonBean;
import com.wocai.jrt.orgadmin.employee.model.EmployeeCommissionHistory;
import com.wocai.jrt.orgadmin.employee.model.EmployeeGroup;
import com.wocai.jrt.orgadmin.employee.model.GroupMember;
import com.wocai.jrt.orgadmin.employee.service.spi.EmployeeCommissionHistoryService;
import com.wocai.jrt.orgadmin.employee.service.spi.EmployeeGroupService;
import com.wocai.jrt.orgadmin.employee.service.spi.EmployeeService;
import com.wocai.jrt.orgadmin.employee.service.spi.GroupMemberService;
import com.wocai.jrt.orgadmin.employee.service.spi.OrgService;
import com.wocai.jrt.orgadmin.investor.service.spi.InvestorService;
import com.wocai.jrt.orgadmin.investor.service.spi.RiskDisclosureService;
import com.wocai.jrt.orgadmin.orders.model.Orders;
import com.wocai.jrt.orgadmin.orders.model.OrdersBean;
import com.wocai.jrt.orgadmin.orders.service.spi.OrdersService;
import com.wocai.jrt.orgadmin.pay.dao.AuditRecordDao;
import com.wocai.jrt.orgadmin.pay.model.AuditRecord;
import com.wocai.jrt.orgadmin.pay.model.AuditRecordBean;
import com.wocai.jrt.orgadmin.pay.service.spi.AuditRecordService;
import com.wocai.jrt.orgadmin.product.bean.ProductReqBean;
import com.wocai.jrt.orgadmin.product.model.Product;
import com.wocai.jrt.orgadmin.product.service.spi.ProductService;
import com.wocai.jrt.orgadmin.setting.model.Setting;
import com.wocai.jrt.orgadmin.setting.service.spi.SettingService;
import com.wocai.jrt.orgadmin.utils.ApiCallUtils;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 订单审核记录相关的service业务实现。
 * 
 * @author yinlei
 * @date 2015-11-19 16:04:02
 */
@Named
public class AuditRecordServiceImpl extends
		MyBatisServiceImpl<AuditRecord, AuditRecordBean, String> implements AuditRecordService {
	// 添加了方法后，记得改为private
	protected AuditRecordDao auditRecordDao;

	private static final Logger LOGGER = LoggerFactory.getLogger(AuditRecordServiceImpl.class);

	private static final int STATE_COMPLETE = 6;
	@Inject
	private OrdersService ordersServiceImpl;
	@Inject
	private EmployeeService employeeServiceImpl;

	@Inject
	private ProductService productServiceImpl;
	@Inject
	private EmployeeGroupService employeeGroupServiceImpl;
	@Inject
	private GroupMemberService groupMemberServiceImpl;
	@Inject
	private EmployeeCommissionHistoryService employeeCommissionHistoryServiceImpl;
	@Inject
	private InvestorService investorServiceImpl;
	@Inject
	private RiskDisclosureService riskDisclosureServiceImpl;
	@Inject
	private SettingService settingServiceImpl;
	@Inject
	private OrgService orgServiceImpl;

	@Override
	@Inject
	public void setBaseDao(BaseDao<AuditRecord, AuditRecordBean, String> auditRecordDao) {
		this.baseDao = auditRecordDao;
		this.auditRecordDao = (AuditRecordDao) auditRecordDao;
	}

	@Override
	public JsonBean auditOrder(AuditRecord model) {
		JsonBean bean = new JsonBean();
		try {
			model.setAuditTime(DateUtils.getNow());
			model.setEmployeeId(UserUtils.getUserId());
			model.setId(ObjectId.get().toString());
			model.setEmployeeName(employeeServiceImpl.get(UserUtils.getUserId()).getName());
			model.setOrgId(UserUtils.getOrgId());
			OrdersBean ob = new OrdersBean();
			ob.createCriteria().andOrderIdEqualTo(model.getOrderId());
			Orders o = null;
			try {
				o = ordersServiceImpl.pagedForList(ob).get(0);
			} catch (Exception e) {
				bean.setMessage("error");
				bean.setCode(0);
				LOGGER.error("订单编号错误");
				return bean;
			}
			if (true == model.getPass()) {
				
				// 生成电子合同
				try {
					String orderId = o.getOrderId();
					Setting setting = new Setting();
					setting.setKeyName("orderRevisit");
					setting.setOrgId(o.getOrgId());
					Setting getSetting = settingServiceImpl.unique(setting);

					// 0-不需要回访主流程继续
					if ("0".equals(getSetting.getKeyValue())) {
						int code = ApiCallUtils.callToCreateContact(orderId);
						if (code != 1) {
							throw new ServiceException("调用api生成合同失败");
						}
					}

				}  catch (ServiceException e) {
					LOGGER.error("createContact error, msg=[{}]", e.getMessage());
					throw e;
				} catch (Exception e) {
					LOGGER.error("createContact error, msg=[{}]", e.getMessage());
				} 

				// 支付凭证审核状态设为审核成功 订单状态设为已完成
				o.setAuditState(3);
				o.setState(STATE_COMPLETE);
				// 佣金生成
				ProductReqBean req = new ProductReqBean();
				req.setProductId(o.getProductId());
				req.setEmployeeId(o.getEmployeeId());
				Product pd = productServiceImpl.getDetail(req);

				// 查找是否为理财师团队长
				EmployeeGroup eg = new EmployeeGroup();
				eg.setEmployeeId(o.getEmployeeId());
				eg.setDeleted(false);
				EmployeeGroup employeeGroup = employeeGroupServiceImpl.unique(eg);

				EmployeeCommissionHistory employeeCommissionHistory = new EmployeeCommissionHistory();
				employeeCommissionHistory.setId(ObjectId.get().toString());
				employeeCommissionHistory.setOrderId(o.getOrderId());
				employeeCommissionHistory.setProductId(o.getProductId());
				try {
					if (StringUtils.isBlank(pd.getCommissionRate().toString())) {
						LOGGER.error("commission rate is none");
						bean.setMessage("设置的产品佣金分成有误，请确认后重试");
						bean.setCode(0);
						return bean;
					}
				} catch (Exception e) {
					LOGGER.error("commission rate is none");
					bean.setMessage("设置的产品佣金分成有误，请确认后重试");
					bean.setCode(0);
					return bean;
				}
				employeeCommissionHistory.setCommissionRate(pd.getCommissionRate());
				employeeCommissionHistory.setCommission(BigDecimalUtils.multiply(
						o.getOrderAmount(), pd.getCommissionRate()));
				employeeCommissionHistory.setEmployeeId(o.getEmployeeId());
				employeeCommissionHistory.setCreateTime(new Date());

				if (null != employeeGroup && employeeGroup.getPlannerGroup()) {
					if (StringUtils.isBlank(pd.getDividendRate().toString())) {
						LOGGER.error("dividend rate is none");
						bean.setMessage("设置的产品佣金分成有误，请确认后重试");
						bean.setCode(0);
						return bean;
					}
					employeeCommissionHistory.setDividendRate(pd.getDividendRate());
					employeeCommissionHistory.setDividend(BigDecimalUtils.multiply(
							o.getOrderAmount(), pd.getDividendRate()));
				} else {
					// 不是团队长，也要插入团队长的提成
					String teamleaderEmId = null;
					try {
						GroupMember gmParam = new GroupMember();
						gmParam.setEmployeeId(o.getEmployeeId());
						String groupId = groupMemberServiceImpl.unique(gmParam).getGroupId();

						teamleaderEmId = employeeGroupServiceImpl.get(groupId).getEmployeeId();
					} catch (Exception e1) {
						LOGGER.error(
								"employee existed multi group error/employee not existed a group error, msg = [{}]",
								e1.getMessage());
						throw new ServiceException(e1.getMessage());
					}

					if (null != teamleaderEmId) {
						ProductReqBean productReqBean1 = new ProductReqBean();
						productReqBean1.setProductId(o.getProductId());
						productReqBean1.setEmployeeId(teamleaderEmId);
						Product productDetail1 = productServiceImpl.getDetail(productReqBean1);

						EmployeeCommissionHistory teamleaderECH = new EmployeeCommissionHistory();
						teamleaderECH.setId(ObjectId.get().toString());
						teamleaderECH.setOrderId(o.getOrderId());
						teamleaderECH.setProductId(o.getProductId());
						teamleaderECH.setEmployeeId(teamleaderEmId);
						teamleaderECH.setCreateTime(new Date());

						teamleaderECH.setDividendRate(productDetail1.getDividendRate());
						teamleaderECH.setDividend(BigDecimalUtils.multiply(o.getOrderAmount(),
								productDetail1.getDividendRate()));
						teamleaderECH.setState(0);
						employeeCommissionHistoryServiceImpl.save(teamleaderECH);
						LOGGER.info(
								"save employee's teamleader divedend success, teamleaderEmployeeId = [{}]",
								teamleaderEmId);
					}
				}

				employeeCommissionHistory.setState(0);
				employeeCommissionHistoryServiceImpl.save(employeeCommissionHistory);
				LOGGER.info("save employee's commission/devidend success, employeeId = [{}]",
						o.getEmployeeId());
			} else {
				// 支付凭证审核状态设为审核失败
				o.setAuditState(2);
				// o.setState(2);
			}
			int r = ordersServiceImpl.updateById(o);
			if (1 > r) {
				bean.setMessage("修改订单审核状态失败，请联系相关人员");
				bean.setCode(0);
				LOGGER.info("修改订单审核状态失败，请联系相关人员");
				return bean;
			}
			int result = this.save(model);
			if (result == 1) {
				bean.setMessage("success");
				bean.setCode(1);
				LOGGER.info("save record success.");
			} else {
				bean.setMessage("error");
				LOGGER.error("save record error.");
			}
		} catch (Exception e) {
			LOGGER.error("save record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage("error");
			throw new ServiceException(e.getMessage());
		}
		return bean;
	}
}
